package com.zzq.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzq.config.RedisConfig;
import com.zzq.exception.NormalException;
import com.zzq.exception.PhoneException;
import com.zzq.exception.SwitchException;
import com.zzq.exception.ZzqException;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.zzq.enumerate.RedisKeyEnum.SMILE_ACCESSTOKEN;
@Component
@EnableScheduling
@Slf4j
public class AccessTokenUtil {


    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.appsecret}")
    private String appsecret;
    @Value("${wx.accesstoken.url}")
    private String accessTokenUrl;
    @Autowired
    RedisCache redisCache;
    @Value("${wx.generateAccessTokenSwitch}")
    private Boolean generateAccessTokenSwitch;

    @Value("${wx.phonenumber.url}")
    private String phoneNumberUrl;
    @Scheduled(fixedDelay = 3600000)
    private void generateAccessToken(){

        if (generateAccessTokenSwitch) {
            Map<String, Object> wxMap = new HashMap<>();
            wxMap.put("appid", appid);
            wxMap.put("secret", appsecret);
            wxMap.put("grant_type", "client_credential");
            String accessTokenRes = HttpUtil.createGet(accessTokenUrl).form(wxMap).execute().body();
            JSONObject accessTokenJson = JSON.parseObject(accessTokenRes);
            String accessToken = String.valueOf(accessTokenJson.get("access_token"));
            log.info("获取微信AccessToken:{}" , accessToken);
            redisCache.setCacheObject(SMILE_ACCESSTOKEN.key(), accessToken, 7200);
        }
    }

    public String getAccessToken(){
        String accessToken = redisCache.getCacheObject(SMILE_ACCESSTOKEN.key());
        if (ObjectUtils.isEmpty(accessToken)){
            throw  new NormalException("AccessToken无效异常");
        }
        return  accessToken;
    }

    public String getWxPhoneNum(String phoneCode){
        if (generateAccessTokenSwitch) {
            String phoneNumber;
            String accessToken = getAccessToken();
            Map<String, Object> phoneMap = new HashMap<>();
            phoneMap.put("code", phoneCode);
            StringBuilder phoneNumberUrlBuilder = new StringBuilder(phoneNumberUrl);
            phoneNumberUrlBuilder.append("?access_token=").append(accessToken);
            String phoneNumberRes = HttpUtil.createPost(phoneNumberUrlBuilder.toString()).body(JSON.toJSONString(phoneMap), "application/json").execute().body();
            JSONObject phoneNumberJson = JSON.parseObject(phoneNumberRes);
            String errcode = String.valueOf(phoneNumberJson.get("errcode"));
            System.out.println(phoneNumberJson.toJSONString());
            if (errcode.equals("0")) {
                String phoneInfoObject = String.valueOf(phoneNumberJson.get("phone_info"));
                JSONObject phoneInfoJson = JSON.parseObject(phoneInfoObject);
                phoneNumber = String.valueOf(phoneInfoJson.get("purePhoneNumber"));
                return phoneNumber;
            } else {
                throw new PhoneException("登录失败,手机号获取异常");
            }
        }else {
            throw new SwitchException("测试版功能不开启");
        }
    }




}
